# -*- coding: utf-8 -*-
from django import template

register = template.Library()

@register.inclusion_tag('snippet/paginator.html', takes_context=True)
def paginator(context, queryparam , adjacent_pages=2):
    """
    To be used in conjunction with the object_list generic view.

    Adds pagination context variables for use in displaying first, adjacent and
    last page links in addition to those created by the object_list generic
    view.

    """
    
    #queryparam = context['queryparam']
    
    startPage = max( int(queryparam['qpage']) - adjacent_pages, 1)
    if startPage <= 3: startPage = 1
    endPage = int(queryparam['qpage']) + adjacent_pages + 1
    if endPage >= int(queryparam['pagecount']) - 1: endPage = int(queryparam['pagecount']) + 1
    page_numbers = [n for n in range(startPage, endPage) \
            if n > 0 and n <= int(queryparam['pagecount'])]
    
    #page_obj = context['page_obj']
    #paginator = context['paginator']
    
    has_next = (int(queryparam['qpage']) + 1) <=int(queryparam['pagecount'])
    next_page = int(queryparam['qpage']) + 1
    has_previous = (int(queryparam['qpage']) - 1) >= 1
    previous_page = int(queryparam['qpage']) - 1
    first_this_page = int(queryparam['pagesize'])* (int(queryparam['qpage'])-1)
    last_this_page = min(int(queryparam['pagesize'])* int(queryparam['qpage']) ,int(queryparam['record_count']) )
    return {
        #'page_obj': page_obj,
        #'paginator': paginator,
        'hits': queryparam['record_count'],
        'results_per_page': queryparam['pagesize'],
        'page': int(queryparam['qpage']),
        #'pages': queryparam['pagecount'],
        'page_numbers': page_numbers,
        'next': next_page,
        'previous': previous_page,
        'has_next': has_next,
        'has_previous': has_previous,
        'show_first': 1 not in page_numbers and len(page_numbers)>0,
        'show_last': int(queryparam['record_count']) not in page_numbers and len(page_numbers)>0,
        'queryparam':queryparam,
        'first_this_page':first_this_page,
        'last_this_page':last_this_page,
        
    }
